package com.zenithmind.gateway.filter;

import com.zenithmind.common.constant.CommonConstants;
import com.zenithmind.common.security.JwtUtils;
import com.zenithmind.gateway.config.SecurityConfig;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Map;

/**
 * 网关统一认证过滤器
 * 整合多个认证相关过滤器的功能:
 * 1. 提取并解析JWT令牌
 * 2. 将用户信息转发给下游服务
 * 3. 为公开路径添加访客身份信息
 * 4. 添加网关验证标记
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class GatewayAuthFilter implements GlobalFilter, Ordered {

    private final SecurityConfig securityConfig;
    
    @Value("${zenithmind.gateway.auth.enabled:true}")
    private boolean authEnabled;

    // 用户信息相关常量
    private static final String USER_ID_HEADER = "X-User-ID";
    private static final String USER_ROLES_HEADER = "X-User-Roles";
    private static final String AUTH_HEADER = "Authorization";
    
    // 网关验证头，表示请求已通过网关验证
    private static final String GATEWAY_VERIFIED_HEADER = "X-Gateway-Verified";
    // 内部令牌，微服务之间信任的标识
    private static final String INTERNAL_TOKEN_VALUE = "trusted-internal-request";

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        String method = request.getMethod().name();
        
        log.debug("GatewayAuthFilter处理请求: {} {}", method, path);
        
        // 如果认证功能未启用，直接放行
        if (!authEnabled) {
            log.debug("认证功能未启用，直接放行请求: {}", path);
            return chain.filter(exchange);
        }
        
        ServerHttpRequest.Builder requestBuilder = request.mutate();
        
        // 1. 添加网关验证头，表示该请求来自网关
        requestBuilder.header(GATEWAY_VERIFIED_HEADER, INTERNAL_TOKEN_VALUE);
        
        // 2. 检查是否是公开路径但需要添加访客身份
        boolean isPublicPathNeedingAuthRelay = isPublicPathNeedingAuthRelay(path);
        
        // 3. 获取token
        String token = extractToken(request);
        
        if (StringUtils.isBlank(token)) {
            // 如果没有token但是公开路径需要访客身份
            if (isPublicPathNeedingAuthRelay) {
                requestBuilder.header(AUTH_HEADER, "Bearer guest-token-for-public-endpoints");
                requestBuilder.header(USER_ID_HEADER, "guest");
                requestBuilder.header(USER_ROLES_HEADER, "ROLE_GUEST");
                log.debug("为公开路径{}添加模拟访客认证信息", path);
            }
        } else {
            // 如果有token，尝试解析
            try {
                // 使用JwtUtils解析token并提取用户信息
                Map<String, Object> claims = JwtUtils.parseToken(token);
                log.debug("Token解析成功: {}", claims.keySet());

                // 提取用户ID
                String userId = JwtUtils.extractUserIdFromClaims(claims);
                
                // 提取用户角色
                String userRoles = JwtUtils.extractUserRolesFromClaims(claims);
                
                // 将用户信息传递到下游服务
                if (StringUtils.isNotBlank(userId)) {
                    requestBuilder.header(CommonConstants.USER_ID_HEADER, userId);
                    requestBuilder.header(USER_ID_HEADER, userId);
                }
                if (StringUtils.isNotBlank(userRoles)) {
                    requestBuilder.header(CommonConstants.USER_ROLES_HEADER, userRoles);
                    requestBuilder.header(USER_ROLES_HEADER, userRoles);
                }
                
                log.debug("token解析成功，转发请求: {}, 用户ID: {}", path, userId);
            } catch (Exception e) {
                // Token解析失败，记录日志但继续处理
                log.warn("Token解析失败，但仍放行请求: {}, 错误: {}", path, e.getMessage());
            }
        }
        
        // 使用修改后的请求继续处理链
        ServerHttpRequest modifiedRequest = requestBuilder.build();
        return chain.filter(exchange.mutate().request(modifiedRequest).build());
    }
    
    /**
     * 从请求中提取token
     */
    private String extractToken(ServerHttpRequest request) {
        // 首先尝试从token头获取
        String token = request.getHeaders().getFirst("token");
        
        // 如果没有，尝试从Authorization头获取
        if (StringUtils.isBlank(token)) {
            String authHeader = request.getHeaders().getFirst("Authorization");
            if (StringUtils.isNotBlank(authHeader)) {
                if (authHeader.startsWith("Bearer ")) {
                    token = authHeader.substring(7);
                } else if (authHeader.startsWith(CommonConstants.TOKEN_PREFIX)) {
                    token = authHeader.replace(CommonConstants.TOKEN_PREFIX, "");
                }
            }
        } else if (token.startsWith(CommonConstants.TOKEN_PREFIX)) {
            token = token.replace(CommonConstants.TOKEN_PREFIX, "");
        }
        
        return token;
    }
    
    /**
     * 判断给定路径是否是需要中继认证信息的公开路径
     */
    private boolean isPublicPathNeedingAuthRelay(String path) {
        return path.contains("/api/zenithMind/course/") || 
               path.contains("/api/zenithMind/courses/") ||
               (path.startsWith("/api/zenithMind/") && 
                (path.contains("/public/") || path.contains("/statistics/")));
    }

    @Override
    public int getOrder() {
        return -100; // 高优先级，确保在其他过滤器之前执行
    }
} 